//app.js

const config = require('./config/config.js');

App({
  onLaunch: function () {

    //为了单页面调用userId提前准备
    const userId = wx.getStorageSync('userId');
    if(userId){
      this.globalData.userId = userId;
    }
    // else{
    //   wx.showToast({
    //     title: '登录状态失效或者丢失',
    //     success:() =>{
    //       wx.redirectTo({
    //         url: '../../pages/index/index',
    //       });
    //     }
    //   });
    // }

    //验证是否过期，过期则重新登录获取userId，否则则调用内存中userId获取用户信息
    (() => {
      wx.showLoading({
        title: '验证用户状态',
      });
      wx.checkSession({ //检测当前用户的session_key是否过期
        success: () => { //session_key 未过期，并且在本生命周期一直有效
          console.log("登录未过期")
          this.getUserInfo();
        },
        fail: () => { //session_key 已经失效，需要重新执行登录流程
          console.log("登录过期");
          this.login();
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    })();
  },
  // 登录
  login() {
    console.log('login');
    new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          if (res.code) {
            resolve(res.code);
          } else {
            console.log('获取用户登录态失败！' + res.errMsg);
          }
        }
      })
    }).then(code => {
      this.globalData.loginCode = code;
      this.request('/User/Login','POST',`"${code}"`,
        res => {
          this.globalData.userId = res.userId;
          wx.setStorageSync('userId',res.userId);
          if (this.userInfoReadyCallback) {
            this.userInfoReadyCallback(res)
          }
        },'登录失败');
      });
  },
  //获取用户信息
  getUserInfo() {
    // 获取用户信息
    new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            resolve();
          }
        }
      });
    }).then(() => {
      // 已经授权，可以直接调用 getUserInfo 获取头像昵称
      wx.getUserInfo({
        success: data => {
          this.globalData.userId = wx.getStorageSync('userId');
          var userInfo = data.userInfo;

          this.updateUserInfo({
            userId: this.globalData.userId,
            headPortrait: userInfo.avatarUrl,
            nickName: userInfo.nickName,
            sex: userInfo.gender
          })
            .then(this.queryUsreInfo);
        },
        fail: () => { console.log(fail) }
      });
    });
  },
  queryUsreInfo: function () {
    var userId = this.globalData.userId;
    return  new Promise((resolve,reject) => {
      this.request('/User/UserInfo', 'GET', { userId: userId },
        res => {
          this.globalData.userInfo = res;
          resolve(res);
          console.log('this.globalData.userInfo', this.globalData.userInfo);
          if (!res.phoneNumber){
            wx.redirectTo({
              url: '../login/login',
            });
          }
        },'获取用户数据失败');
    });
    
  },

  updateUserInfo:function(targetInfo){
    return new Promise((resolve,reject) => {
      this.request('/User/UpUserInfo', 'PUT', targetInfo, 
        res => { resolve(res);}, '更新用户信息失败');
    });
  },  
  /**
   * 统一请求接口
   */
  request: function (path, method, data, success, fail) {
    const failcallback = function (err) {
      if (typeof (fail) === 'string') {
        wx.showModal({
          title: fail,
          content: err.data.msg,
          showCancel: false
        })
      } else if (typeof (fail) === 'function') {
        fail(err);
      }else{
        console.log(err);
      }
    };
    //将某些接口排除loading
    // if (path !== 'CustomizeInheritBase/GetWeiXinOpenId') {
    //   wx.showLoading();
    // }
    wx.showLoading();
    wx.request({
      url: 'https://www.shencheyi.com/api/v1' + path,
      method: method,
      data: data,
      success: function (res) {
        if (res.data.code >= 200 && res.data.code < 300) {
          success && success(res.data.data);
        } else {
          failcallback(res);
        }
      },
      fail: failcallback,
      complete: function () {
        wx.hideLoading();
      }
    })
  },

  globalData: {
    userInfo: null
  }
})